import React, { useState, useEffect } from 'react';
import {
  Card,
  Steps,
  Upload,
  Button,
  Table,
  Row,
  Col,
  Progress,
  Alert,
  Space,
  Select,
  Input,
  Checkbox,
  Tag,
  Modal,
  message,
  Divider,
  Statistic,
  Tabs,
  Form,
  Radio
} from 'antd';
import {
  InboxOutlined,
  UploadOutlined,
  FileTextOutlined,
  DatabaseOutlined,
  EyeOutlined,
  CheckCircleOutlined,
  ExclamationCircleOutlined,
  LoadingOutlined,
  DownloadOutlined,
  ShareAltOutlined,
  NodeIndexOutlined
} from '@ant-design/icons';
import ReactECharts from 'echarts-for-react';

const { Dragger } = Upload;
const { Option } = Select;
const { TextArea } = Input;
const { TabPane } = Tabs;

const DataImport = () => {
  const [currentStep, setCurrentStep] = useState(0);
  const [uploadedFile, setUploadedFile] = useState(null);
  const [parseResult, setParseResult] = useState(null);
  const [extractedEntities, setExtractedEntities] = useState([]);
  const [extractedRelations, setExtractedRelations] = useState([]);
  const [importProgress, setImportProgress] = useState(0);
  const [isProcessing, setIsProcessing] = useState(false);
  const [previewVisible, setPreviewVisible] = useState(false);
  const [selectedEntities, setSelectedEntities] = useState([]);
  const [selectedRelations, setSelectedRelations] = useState([]);
  const [form] = Form.useForm();

  // 步骤配置
  const steps = [
    {
      title: '上传文件',
      description: '选择要导入的数据文件',
      icon: <UploadOutlined />
    },
    {
      title: '数据解析',
      description: '解析文件内容和结构',
      icon: <FileTextOutlined />
    },
    {
      title: '实体识别',
      description: '识别和提取实体信息',
      icon: <NodeIndexOutlined />
    },
    {
      title: '关系抽取',
      description: '分析和建立实体关系',
      icon: <ShareAltOutlined />
    },
    {
      title: '预览确认',
      description: '预览知识图谱结构',
      icon: <EyeOutlined />
    },
    {
      title: '导入完成',
      description: '执行导入并生成图谱',
      icon: <CheckCircleOutlined />
    }
  ];

  // 模拟数据
  const mockEntities = [
    {
      id: '1',
      name: '人工智能',
      type: 'concept',
      confidence: 0.95,
      description: '模拟人类智能的科学技术',
      attributes: { category: '技术领域', importance: '核心' },
      selected: true
    },
    {
      id: '2',
      name: '张三',
      type: 'person',
      confidence: 0.88,
      description: '人工智能研究员',
      attributes: { position: '研究员', department: '技术部' },
      selected: true
    },
    {
      id: '3',
      name: '腾讯公司',
      type: 'organization',
      confidence: 0.92,
      description: '互联网科技公司',
      attributes: { industry: '互联网', location: '深圳' },
      selected: true
    },
    {
      id: '4',
      name: 'PyTorch',
      type: 'tool',
      confidence: 0.85,
      description: '深度学习框架',
      attributes: { category: '开发工具', language: 'Python' },
      selected: false
    }
  ];

  const mockRelations = [
    {
      id: '1',
      source: '张三',
      target: '腾讯公司',
      type: 'works_for',
      confidence: 0.90,
      description: '张三在腾讯公司工作',
      attributes: { position: '研究员', startDate: '2020-01-01' },
      selected: true
    },
    {
      id: '2',
      source: '张三',
      target: '人工智能',
      type: 'researches',
      confidence: 0.85,
      description: '张三研究人工智能领域',
      attributes: { expertise: '机器学习', years: '5' },
      selected: true
    },
    {
      id: '3',
      source: '张三',
      target: 'PyTorch',
      type: 'uses',
      confidence: 0.78,
      description: '张三使用PyTorch进行开发',
      attributes: { proficiency: '熟练', usage: '日常开发' },
      selected: false
    }
  ];

  // 文件上传处理
  const handleUpload = (info) => {
    const { status, originFileObj } = info.file;
    
    if (status === 'uploading') {
      setIsProcessing(true);
      return;
    }
    
    if (status === 'done') {
      setUploadedFile(originFileObj);
      setIsProcessing(false);
      message.success(`${info.file.name} 文件上传成功`);
      
      // 模拟文件解析
      setTimeout(() => {
        setParseResult({
          fileName: info.file.name,
          fileSize: info.file.size,
          fileType: info.file.type,
          recordCount: 1250,
          columnCount: 8,
          encoding: 'UTF-8'
        });
        setCurrentStep(1);
      }, 1000);
    } else if (status === 'error') {
      setIsProcessing(false);
      message.error(`${info.file.name} 文件上传失败`);
    }
  };

  // 开始数据解析
  const handleParse = () => {
    setIsProcessing(true);
    setCurrentStep(2);
    
    // 模拟解析过程
    setTimeout(() => {
      setExtractedEntities(mockEntities);
      setSelectedEntities(mockEntities.filter(e => e.selected).map(e => e.id));
      setIsProcessing(false);
      message.success('实体识别完成');
    }, 2000);
  };

  // 开始关系抽取
  const handleExtractRelations = () => {
    setIsProcessing(true);
    setCurrentStep(3);
    
    setTimeout(() => {
      setExtractedRelations(mockRelations);
      setSelectedRelations(mockRelations.filter(r => r.selected).map(r => r.id));
      setIsProcessing(false);
      setCurrentStep(4);
      message.success('关系抽取完成');
    }, 2000);
  };

  // 执行导入
  const handleImport = () => {
    setIsProcessing(true);
    setCurrentStep(5);
    setImportProgress(0);
    
    // 模拟导入进度
    const timer = setInterval(() => {
      setImportProgress(prev => {
        if (prev >= 100) {
          clearInterval(timer);
          setIsProcessing(false);
          message.success('知识图谱导入完成！');
          return 100;
        }
        return prev + 10;
      });
    }, 300);
  };

  // 实体表格列配置
  const entityColumns = [
    {
      title: '实体名称',
      dataIndex: 'name',
      render: (text, record) => (
        <Space>
          <Tag color={getTypeColor(record.type)}>{getTypeLabel(record.type)}</Tag>
          {text}
        </Space>
      )
    },
    {
      title: '置信度',
      dataIndex: 'confidence',
      width: 100,
      render: confidence => (
        <Progress 
          percent={Math.round(confidence * 100)} 
          size="small" 
          status={confidence > 0.8 ? 'success' : confidence > 0.6 ? 'normal' : 'exception'}
        />
      )
    },
    {
      title: '描述',
      dataIndex: 'description',
      ellipsis: true
    },
    {
      title: '操作',
      width: 80,
      render: (_, record) => (
        <Button 
          type="link" 
          size="small" 
          icon={<EyeOutlined />}
          onClick={() => showEntityDetail(record)}
        >
          详情
        </Button>
      )
    }
  ];

  // 关系表格列配置
  const relationColumns = [
    {
      title: '源实体',
      dataIndex: 'source',
      render: text => <Tag color="blue">{text}</Tag>
    },
    {
      title: '关系类型',
      dataIndex: 'type',
      render: type => <Tag color="purple">{getRelationLabel(type)}</Tag>
    },
    {
      title: '目标实体',
      dataIndex: 'target',
      render: text => <Tag color="green">{text}</Tag>
    },
    {
      title: '置信度',
      dataIndex: 'confidence',
      width: 100,
      render: confidence => (
        <Progress 
          percent={Math.round(confidence * 100)} 
          size="small" 
          status={confidence > 0.8 ? 'success' : 'normal'}
        />
      )
    },
    {
      title: '操作',
      width: 80,
      render: (_, record) => (
        <Button 
          type="link" 
          size="small" 
          icon={<EyeOutlined />}
          onClick={() => showRelationDetail(record)}
        >
          详情
        </Button>
      )
    }
  ];

  // 辅助函数
  const getTypeColor = (type) => {
    const colors = {
      concept: 'purple',
      person: 'green',
      organization: 'red',
      tool: 'orange',
      location: 'blue'
    };
    return colors[type] || 'default';
  };

  const getTypeLabel = (type) => {
    const labels = {
      concept: '概念',
      person: '人物',
      organization: '组织',
      tool: '工具',
      location: '位置'
    };
    return labels[type] || type;
  };

  const getRelationLabel = (type) => {
    const labels = {
      works_for: '工作于',
      researches: '研究',
      uses: '使用',
      located_in: '位于',
      part_of: '属于'
    };
    return labels[type] || type;
  };

  const showEntityDetail = (entity) => {
    Modal.info({
      title: '实体详情',
      width: 600,
      content: (
        <div>
          <p><strong>名称：</strong>{entity.name}</p>
          <p><strong>类型：</strong><Tag color={getTypeColor(entity.type)}>{getTypeLabel(entity.type)}</Tag></p>
          <p><strong>置信度：</strong>{(entity.confidence * 100).toFixed(1)}%</p>
          <p><strong>描述：</strong>{entity.description}</p>
          <Divider />
          <p><strong>属性信息：</strong></p>
          {Object.entries(entity.attributes).map(([key, value]) => (
            <p key={key}><strong>{key}：</strong>{value}</p>
          ))}
        </div>
      )
    });
  };

  const showRelationDetail = (relation) => {
    Modal.info({
      title: '关系详情',
      width: 600,
      content: (
        <div>
          <p><strong>关系：</strong>
            <Tag color="blue">{relation.source}</Tag>
            <span style={{ margin: '0 8px' }}>→</span>
            <Tag color="green">{relation.target}</Tag>
          </p>
          <p><strong>类型：</strong><Tag color="purple">{getRelationLabel(relation.type)}</Tag></p>
          <p><strong>置信度：</strong>{(relation.confidence * 100).toFixed(1)}%</p>
          <p><strong>描述：</strong>{relation.description}</p>
          <Divider />
          <p><strong>属性信息：</strong></p>
          {Object.entries(relation.attributes).map(([key, value]) => (
            <p key={key}><strong>{key}：</strong>{value}</p>
          ))}
        </div>
      )
    });
  };

  // 统计数据
  const getStatistics = () => {
    const selectedEntityCount = selectedEntities.length;
    const selectedRelationCount = selectedRelations.length;
    const entityTypes = [...new Set(extractedEntities.filter(e => selectedEntities.includes(e.id)).map(e => e.type))].length;
    
    return { selectedEntityCount, selectedRelationCount, entityTypes };
  };

  const stats = getStatistics();

  return (
    <div style={{ padding: 24, background: '#f5f5f5' }}>
      {/* 步骤导航 */}
      <Card style={{ marginBottom: 24, borderRadius: 8 }}>
        <Steps current={currentStep} items={steps} />
      </Card>

      {/* 步骤内容 */}
      {currentStep === 0 && (
        <Card title="上传数据文件" style={{ borderRadius: 8 }}>
          <Row gutter={24}>
            <Col span={16}>
              <Dragger
                name="file"
                multiple={false}
                accept=".csv,.xlsx,.xls,.json,.txt,.pdf"
                customRequest={({ file, onSuccess }) => {
                  setTimeout(() => onSuccess("ok"), 1000);
                }}
                onChange={handleUpload}
                style={{ padding: '40px 20px' }}
              >
                <p className="ant-upload-drag-icon">
                  <InboxOutlined style={{ fontSize: 48, color: '#1890ff' }} />
                </p>
                <p className="ant-upload-text" style={{ fontSize: 16, marginBottom: 8 }}>
                  点击或拖拽文件到此区域上传
                </p>
                <p className="ant-upload-hint" style={{ color: '#666' }}>
                  支持 CSV、Excel、JSON、TXT、PDF 格式文件，单个文件不超过 100MB
                </p>
              </Dragger>
              
              {isProcessing && (
                <div style={{ textAlign: 'center', marginTop: 20 }}>
                  <LoadingOutlined style={{ fontSize: 24, color: '#1890ff' }} />
                  <p style={{ marginTop: 8 }}>正在上传文件...</p>
                </div>
              )}
            </Col>
            
            <Col span={8}>
              <Card title="支持格式" size="small">
                <Space direction="vertical" style={{ width: '100%' }}>
                  <div><FileTextOutlined /> CSV 文件 - 结构化数据</div>
                  <div><FileTextOutlined /> Excel 文件 - 表格数据</div>
                  <div><FileTextOutlined /> JSON 文件 - 半结构化数据</div>
                  <div><FileTextOutlined /> TXT 文件 - 文本数据</div>
                  <div><FileTextOutlined /> PDF 文件 - 文档数据</div>
                </Space>
              </Card>
              
              <Card title="导入示例" size="small" style={{ marginTop: 16 }}>
                <Button type="link" icon={<DownloadOutlined />}>
                  下载 CSV 模板
                </Button>
                <br />
                <Button type="link" icon={<DownloadOutlined />}>
                  下载 JSON 模板
                </Button>
              </Card>
            </Col>
          </Row>
        </Card>
      )}

      {currentStep === 1 && parseResult && (
        <Card title="数据解析结果" style={{ borderRadius: 8 }}>
          <Row gutter={16} style={{ marginBottom: 24 }}>
            <Col span={6}>
              <Statistic title="文件名称" value={parseResult.fileName} />
            </Col>
            <Col span={6}>
              <Statistic title="文件大小" value={`${(parseResult.fileSize / 1024).toFixed(1)} KB`} />
            </Col>
            <Col span={6}>
              <Statistic title="记录数量" value={parseResult.recordCount} />
            </Col>
            <Col span={6}>
              <Statistic title="字段数量" value={parseResult.columnCount} />
            </Col>
          </Row>
          
          <Alert
            message="文件解析成功"
            description="系统已成功解析您上传的文件，可以进行下一步实体识别。"
            type="success"
            showIcon
            style={{ marginBottom: 16 }}
          />
          
          <Space>
            <Button type="primary" onClick={handleParse} loading={isProcessing}>
              开始实体识别
            </Button>
            <Button onClick={() => setCurrentStep(0)}>重新上传</Button>
          </Space>
        </Card>
      )}

      {currentStep === 2 && (
        <Card title="实体识别结果" style={{ borderRadius: 8 }}>
          {isProcessing ? (
            <div style={{ textAlign: 'center', padding: 40 }}>
              <LoadingOutlined style={{ fontSize: 32, color: '#1890ff' }} />
              <p style={{ marginTop: 16, fontSize: 16 }}>正在识别实体...</p>
              <p style={{ color: '#666' }}>AI 正在分析文本内容，识别人物、组织、概念等实体</p>
            </div>
          ) : (
            <>
              <Row gutter={16} style={{ marginBottom: 16 }}>
                <Col span={8}>
                  <Statistic title="识别实体数" value={extractedEntities.length} prefix={<NodeIndexOutlined />} />
                </Col>
                <Col span={8}>
                  <Statistic title="高置信度" value={extractedEntities.filter(e => e.confidence > 0.8).length} />
                </Col>
                <Col span={8}>
                  <Statistic title="实体类型" value={[...new Set(extractedEntities.map(e => e.type))].length} />
                </Col>
              </Row>
              
              <Table
                rowKey="id"
                columns={entityColumns}
                dataSource={extractedEntities}
                rowSelection={{
                  selectedRowKeys: selectedEntities,
                  onChange: setSelectedEntities,
                  getCheckboxProps: (record) => ({
                    disabled: record.confidence < 0.5
                  })
                }}
                pagination={{ pageSize: 10 }}
              />
              
              <div style={{ marginTop: 16, textAlign: 'right' }}>
                <Space>
                  <Button onClick={() => setCurrentStep(1)}>上一步</Button>
                  <Button 
                    type="primary" 
                    onClick={handleExtractRelations}
                    disabled={selectedEntities.length === 0}
                  >
                    开始关系抽取 ({selectedEntities.length} 个实体)
                  </Button>
                </Space>
              </div>
            </>
          )}
        </Card>
      )}

      {currentStep === 3 && (
        <Card title="关系抽取结果" style={{ borderRadius: 8 }}>
          {isProcessing ? (
            <div style={{ textAlign: 'center', padding: 40 }}>
              <LoadingOutlined style={{ fontSize: 32, color: '#1890ff' }} />
              <p style={{ marginTop: 16, fontSize: 16 }}>正在抽取关系...</p>
              <p style={{ color: '#666' }}>AI 正在分析实体间的关系，建立知识图谱连接</p>
            </div>
          ) : null}
        </Card>
      )}

      {currentStep === 4 && (
        <Card title="预览知识图谱" style={{ borderRadius: 8 }}>
          <Tabs defaultActiveKey="1">
            <TabPane tab="关系列表" key="1">
              <Row gutter={16} style={{ marginBottom: 16 }}>
                <Col span={8}>
                  <Statistic title="识别关系数" value={extractedRelations.length} prefix={<ShareAltOutlined />} />
                </Col>
                <Col span={8}>
                  <Statistic title="高置信度" value={extractedRelations.filter(r => r.confidence > 0.8).length} />
                </Col>
                <Col span={8}>
                  <Statistic title="关系类型" value={[...new Set(extractedRelations.map(r => r.type))].length} />
                </Col>
              </Row>
              
              <Table
                rowKey="id"
                columns={relationColumns}
                dataSource={extractedRelations}
                rowSelection={{
                  selectedRowKeys: selectedRelations,
                  onChange: setSelectedRelations
                }}
                pagination={{ pageSize: 10 }}
              />
            </TabPane>
            
            <TabPane tab="图谱预览" key="2">
              <div style={{ height: 400, border: '1px dashed #d9d9d9', borderRadius: 6, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <div style={{ textAlign: 'center', color: '#666' }}>
                  <NodeIndexOutlined style={{ fontSize: 48, marginBottom: 16 }} />
                  <p>知识图谱可视化预览</p>
                  <p style={{ fontSize: 12 }}>将显示 {stats.selectedEntityCount} 个实体和 {stats.selectedRelationCount} 个关系</p>
                </div>
              </div>
            </TabPane>
            
            <TabPane tab="统计分析" key="3">
              <Row gutter={16}>
                <Col span={12}>
                  <Card title="实体类型分布" size="small">
                    <ReactECharts
                      option={{
                        tooltip: { trigger: 'item' },
                        series: [{
                          type: 'pie',
                          radius: ['40%', '70%'],
                          data: [
                            { value: 2, name: '概念', itemStyle: { color: '#722ed1' } },
                            { value: 1, name: '人物', itemStyle: { color: '#52c41a' } },
                            { value: 1, name: '组织', itemStyle: { color: '#f5222d' } },
                            { value: 1, name: '工具', itemStyle: { color: '#faad14' } }
                          ]
                        }]
                      }}
                      style={{ height: '200px' }}
                    />
                  </Card>
                </Col>
                <Col span={12}>
                  <Card title="关系类型分布" size="small">
                    <ReactECharts
                      option={{
                        tooltip: { trigger: 'axis' },
                        xAxis: { type: 'category', data: ['工作关系', '研究关系', '使用关系'] },
                        yAxis: { type: 'value' },
                        series: [{
                          type: 'bar',
                          data: [1, 1, 1],
                          itemStyle: { color: '#1890ff' }
                        }]
                      }}
                      style={{ height: '200px' }}
                    />
                  </Card>
                </Col>
              </Row>
            </TabPane>
          </Tabs>
          
          <div style={{ marginTop: 24, textAlign: 'right' }}>
            <Space>
              <Button onClick={() => setCurrentStep(2)}>上一步</Button>
              <Button 
                type="primary" 
                onClick={handleImport}
                disabled={selectedEntities.length === 0 || selectedRelations.length === 0}
              >
                确认导入 ({stats.selectedEntityCount} 实体, {stats.selectedRelationCount} 关系)
              </Button>
            </Space>
          </div>
        </Card>
      )}

      {currentStep === 5 && (
        <Card title="导入进度" style={{ borderRadius: 8 }}>
          <div style={{ textAlign: 'center', padding: 40 }}>
            {importProgress < 100 ? (
              <>
                <LoadingOutlined style={{ fontSize: 48, color: '#1890ff', marginBottom: 24 }} />
                <h3>正在导入知识图谱...</h3>
                <Progress 
                  percent={importProgress} 
                  style={{ maxWidth: 400, margin: '24px auto' }}
                  strokeColor={{
                    '0%': '#108ee9',
                    '100%': '#87d068',
                  }}
                />
                <p style={{ color: '#666' }}>
                  {importProgress < 30 && '正在创建实体...'}
                  {importProgress >= 30 && importProgress < 60 && '正在建立关系...'}
                  {importProgress >= 60 && importProgress < 90 && '正在优化图谱...'}
                  {importProgress >= 90 && '即将完成...'}
                </p>
              </>
            ) : (
              <>
                <CheckCircleOutlined style={{ fontSize: 48, color: '#52c41a', marginBottom: 24 }} />
                <h3 style={{ color: '#52c41a' }}>知识图谱导入成功！</h3>
                <Row gutter={16} style={{ marginTop: 32, maxWidth: 600, margin: '32px auto 0' }}>
                  <Col span={8}>
                    <Statistic title="导入实体" value={stats.selectedEntityCount} prefix={<NodeIndexOutlined />} />
                  </Col>
                  <Col span={8}>
                    <Statistic title="导入关系" value={stats.selectedRelationCount} prefix={<ShareAltOutlined />} />
                  </Col>
                  <Col span={8}>
                    <Statistic title="实体类型" value={stats.entityTypes} prefix={<DatabaseOutlined />} />
                  </Col>
                </Row>
                
                <div style={{ marginTop: 32 }}>
                  <Space size="large">
                    <Button type="primary" size="large" onClick={() => window.location.href = '/dashboard/knowledge-graph'}>
                      查看知识图谱
                    </Button>
                    <Button size="large" onClick={() => window.location.href = '/dashboard/data-management'}>
                      管理实体数据
                    </Button>
                    <Button size="large" onClick={() => {
                      setCurrentStep(0);
                      setUploadedFile(null);
                      setParseResult(null);
                      setExtractedEntities([]);
                      setExtractedRelations([]);
                      setImportProgress(0);
                    }}>
                      继续导入
                    </Button>
                  </Space>
                </div>
              </>
            )}
          </div>
        </Card>
      )}
    </div>
  );
};

export default DataImport;